package com.example.jm24.ui.home;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.bumptech.glide.Glide;
import com.example.jm24.Data;
import com.example.jm24.DataAdapter;
import com.example.jm24.IntroduceActivity;
import com.example.jm24.MainActivity;
import com.example.jm24.R;
import com.example.jm24.UserDao;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class HomeFragment extends Fragment implements OnBannerListener {

    private HomeViewModel homeViewModel;
    private ListView list,list1;//列表视图对象
    private SearchView s;
    private HomeFragment mContext;//设备上下文
    private List<Data> mData = null;//定义数据列表
    private Banner mBanner;
    private Button btn;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, //内容页面的布局文件
                container,//根视图对象
                false);//false表示需要手动调用addView方法将view添加到contain//true表示不需要手动调用addView方法
        mContext = HomeFragment.this;//初始化设备上下文

        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);//安卓进入页面避免软键盘弹出的解决办法
        final String username = getActivity().getIntent().getStringExtra("username");//需要将数据传递到UserFragment中显示，第一种是直接在Fragment中获取Activity实例然后获取传递的Intent对象，如下
        final String url = getActivity().getIntent().getStringExtra("url");
        list = root.findViewById(R.id.lv);//初始化列表视图对象
        list1 = root.findViewById(R.id.lv1);//初始化列表视图对象
        s = root.findViewById(R.id.sv);//初始化列表视图对象
        mBanner =root.findViewById(R.id.mBanner);
        new Thread() {
            @Override
            public void run() {
                super.run();
                // 耗时操作
                UserDao d = new UserDao();
                mData = new LinkedList<>();//创建数据链表
                mData = d.getData();//给数据链表增加内容
                //Log.i(TAG,"fun");
                //====================
                Handler mHandler = new Handler(Looper.getMainLooper()) {
                    @Override
                    public void handleMessage(@NonNull Message msg) {
                        super.handleMessage(msg);
                        // 切换到主线程
                        //一开始显示
                        list1.setVisibility(View.VISIBLE);
                        DataAdapter mAdapter = new DataAdapter((LinkedList<Data>) mData, mContext);//初始化适配器对象
                        list1.setAdapter(mAdapter);//设置适配器
                        list1.setOnItemClickListener(new AdapterView.OnItemClickListener(){

                            //listview点击事件
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                                    int position, long id) {
                                // TODO Auto-generated method stub
                                //List<Data> list1=new ArrayList<Data>();

                                Data info = mData.get(position);
                                //List<Data>list1=new ArrayList<Data>();
                                Bundle bundle = new Bundle();

                                bundle.putString("name", info.getName());//商家名字
                                //System.out.println("测试1"+info.getName());
                                bundle.putString("housename", info.getHousename());
                                //System.out.println("测试2"+info.getHousename());
                                bundle.putString("username", username);//用户名
                                bundle.putString("url", url);
                                Intent intent = new Intent(getContext(), IntroduceActivity.class);
                                intent.putExtras(bundle);
                                //finish();
                                startActivity(intent);
                            }
                        });

                    }
                };
                mHandler.sendEmptyMessage(0);

            }
        }.start();
        initView();
        //listview启动过滤
        list.setTextFilterEnabled(true);
        //一开始不显示
        list.setVisibility(View.GONE);
        //搜索框不自动缩小为一个搜索图标，而是match_parent
        s.setIconifiedByDefault(false);
        //显示搜索按钮
        s.setSubmitButtonEnabled(true);
        //默认提示文本
        s.setQueryHint("查找");
        s.setOnQueryTextListener(new SearchView.OnQueryTextListener()

        {
            //单击搜索按钮的监听
            @Override
            public boolean onQueryTextSubmit (final String query){
                new Thread() {
                    @Override
                    public void run() {
                        super.run();
                        // 耗时操作
                        UserDao d = new UserDao();
                        mData = new LinkedList<>();//创建数据链表
                        mData = d.getDate(query);//给数据链表增加内容
                        //Log.i(TAG,"fun");
                        System.out.println(mData.size());
                        //====================
                        Handler mHandler = new Handler(Looper.getMainLooper()) {
                            @Override
                            public void handleMessage(@NonNull Message msg) {
                                super.handleMessage(msg);
                                // 切换到主线程
                                DataAdapter mAdapter = new DataAdapter((LinkedList<Data>) mData, mContext);//初始化适配器对象
                                list.setAdapter(mAdapter);//设置适配器
                                list.setOnItemClickListener(new AdapterView.OnItemClickListener(){

                                    @Override
                                    public void onItemClick(AdapterView<?> parent, View view,
                                                            int position, long id) {
                                        // TODO Auto-generated method stub
                                        //List<Data> list1=new ArrayList<Data>();
                                        Data info = mData.get(position);
                                        //List<Data>list1=new ArrayList<Data>();
                                        Bundle bundle = new Bundle();
                                        bundle.putString("name", info.getName());
                                        bundle.putString("housename", info.getHousename());
                                        bundle.putString("username", username);
                                        bundle.putString("url", url);
                                        //bundle.putString("toWhere", info.getToWhere());
                                        //bundle.putString("time",info.getTime());
                                        //bundle.putString("content", info.getContent());
                                        Intent intent = new Intent(getContext(), IntroduceActivity.class);
                                        intent.putExtras(bundle);
                                        //finish();
                                        startActivity(intent);
                                    }
                                });
                            }
                        };
                        mHandler.sendEmptyMessage(0);

                    }
                }.start();
                Toast.makeText(getContext(), "123", Toast.LENGTH_SHORT).show();

                return false;
            }
            //输入字符的监听
            @Override
            public boolean onQueryTextChange (String newText){
                if (TextUtils.isEmpty(newText)) {
                    list.setVisibility(View.GONE);
                    list.clearTextFilter();// 清除ListView的过滤
                } else {
                    //mAdapter.getFilter().filter(newText);//通过适配器过滤
                    list.setVisibility(View.VISIBLE);
                    list.setFilterText(newText);// 使用用户输入的内容对ListView的列表项进行过滤
                    list.dispatchDisplayHint(View.INVISIBLE);//隐藏弹出的黑框
                }

                return true;
            }
        });
        /*final TextView textView = root.findViewById(R.id.text_home);
        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });*/
        return root;
    }

    public void initView() {
        //mBanner = view.findViewById(R.id.mBanner);
        //放置图片
        int[] imageResourceID = new int[]{R.drawable.p1, R.drawable.p2, R.drawable.p3, R.drawable.p4};
        List<Integer> imgeList = new ArrayList<>();
        //设置轮播标题
        String[] mtitle = new String[]{"图1", "图2", "图3", "图4"};
        List<String> titleList = new ArrayList<>();
        for (int i = 0; i < imageResourceID.length; i++) {
            imgeList.add(imageResourceID[i]);//把图片资源循环放入list里面
            titleList.add(mtitle[i]);//把标题循环设置进列表里面
            //设置图片加载器，通过Glide加载图片
            mBanner.setImageLoader(new ImageLoader() {
                @Override
                public void displayImage(Context context, Object path, ImageView imageView) {
                    Glide.with(context).load(path).into(imageView);
                }
            });
            //设置轮播的动画效果,里面有很多种特效,可以到GitHub上查看文档。
            mBanner.setBannerAnimation(Transformer.DepthPage);
            mBanner.setImages(imgeList);//设置图片资源
            mBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR_TITLE_INSIDE);//设置banner显示样式（带标题的样式）
            mBanner.setBannerTitles(titleList); //设置标题集合（当banner样式有显示title时）
            //设置指示器位置（即图片下面的那个小圆点）
            mBanner.setIndicatorGravity(BannerConfig.CENTER);
            mBanner.setDelayTime(3000);//设置轮播时间3秒切换下一图
            mBanner.setOnBannerListener(this);//设置监听
            mBanner.start();//开始进行banner渲染
        }
    }
    @Override
    public void onStart() {
        super.onStart();
        mBanner.startAutoPlay();//开始轮播
    }

    @Override
    public void onStop() {
        super.onStop();
        mBanner.stopAutoPlay();//结束轮播
    }
    //对轮播图设置点击监听事件
    @Override
    public void OnBannerClick(int position) {

        Toast.makeText(getContext(), "你点击了第" + (position + 1) + "张轮播图", Toast.LENGTH_SHORT).show();
    }
}
